package com.sun.entity;

import cn.dev33.satoken.stp.StpUtil;
import com.sun.utils.IdGenerator;
import jakarta.persistence.PrePersist;
import jakarta.persistence.PreUpdate;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;

/**
 * MP自动填充Handler
 *
 * @Author sun
 * @CreateTime 2025/9/2 23:29
 */
@Slf4j
public class CreateAndUpdateListener {

    @PrePersist
    public void preCreate(BaseEntity entity) {
        IdGenerator idGenerator = new IdGenerator();
        //entity.setId(idGenerator.next());
        entity.setCreateTime(LocalDateTime.now());
        log.info(StpUtil.getLoginId().toString());
        entity.setUpdaterId(Long.valueOf(StpUtil.getLoginId().toString()));
        entity.setCreaterId(Long.valueOf(StpUtil.getLoginId().toString()));

        entity.setUpdateTime(LocalDateTime.now());
        log.info(String.valueOf(StpUtil.getExtra(StpUtil.getTokenValue(), "name")));
        entity.setCreaterName(StpUtil.getExtra("name").toString());
        entity.setUpdaterName(StpUtil.getExtra("name").toString());
    }

    @PreUpdate
    public void preUpdate(BaseEntity entity) {
        entity.setUpdateTime(LocalDateTime.now());
        entity.setUpdaterId(Long.valueOf(StpUtil.getLoginId().toString()));
        entity.setUpdaterName(StpUtil.getExtra("name").toString());
    }
}
